# 开发时间 2023/6/17 9:57
import datetime
import os
from tkinter import *
from tkinter.ttk import *
from tkinter import messagebox, ttk
from tkinter import Label, Frame, Tk, Button
from tkinter.filedialog import askopenfilename
from PIL import Image, ImageTk
from main.Student import *
from main.StudentDetails import *
from main.MysqlConnectModule import *
from utils import get_project_path


# 收集添加课时需要的必要数据交给add_course_association_to方法执行
def add_course_association():
    """

    @return:
    """
    dicts_course = {'LEGO': [], 'WEDO': [], 'SCRATCH': [], 'PYTHON': []}
    dicts_student = {'LEGO': [], 'WEDO': [], 'SCRATCH': [], 'PYTHON': []}
    conn = get_connector()
    cur = get_cur(conn)
    data_course = get_data(cur, 'select * from t_course;')
    data_student = get_data(cur, 'select stu_name,session_type from t_student;')
    for i in data_course:
        if i[2] == 'LEGO':
            dicts_course['LEGO'].append(i[1])
        elif i[2] == 'WEDO':
            dicts_course['WEDO'].append(i[1])
        elif i[2] == 'SCRATCH':
            dicts_course['SCRATCH'].append(i[1])
        elif i[2] == 'PYTHON':
            dicts_course['PYTHON'].append(i[1])
    for i in data_student:
        if i[1] == 0:
            dicts_student['LEGO'].append(i[0])
        elif i[1] == 1:
            dicts_student['WEDO'].append(i[0])
        elif i[1] == 2:
            dicts_student['SCRATCH'].append(i[0])
        elif i[1] == 3:
            dicts_student['PYTHON'].append(i[0])
    cur_close(cur)
    conn_close(conn)
    addCourseAssociationWindow = Tk()
    addCourseAssociationWindow.title('添加课时')

    # addWindow.geometry('400x300')
    stuName_label = Label(addCourseAssociationWindow, text='学生姓名：')
    courseName_label = Label(addCourseAssociationWindow, text='课程名称：')
    courseType_label = Label(addCourseAssociationWindow, text='课程类别：')
    date_label = Label(addCourseAssociationWindow, text='上课时间：')
    # sticky='w'，实现两个标签文本左对齐
    stuName_label.grid(row=0, column=0, padx=10, pady=5, sticky='w')
    courseName_label.grid(row=1, column=0, padx=10, pady=5, sticky='w')
    courseType_label.grid(row=2, column=0, padx=10, pady=5, sticky='w')
    date_label.grid(row=3, column=0, padx=10, pady=5, sticky='w')

    # stuName_entry = Entry(addCourseAssociationWindow)
    # 学生名字下拉框
    ddb_cstu = ttk.Combobox(addCourseAssociationWindow)
    ddb_cstu['value'] = ()
    ddb_cstu['state'] = "readonly"
    # 课程名字下拉框
    ddb_cname = ttk.Combobox(addCourseAssociationWindow)
    ddb_cname['value'] = ()
    ddb_cname['state'] = "readonly"
    # courseName_entry = Entry(addCourseAssociationWindow)
    # 课程类型下拉框
    ddb_ctype = ttk.Combobox(addCourseAssociationWindow)
    ddb_ctype['value'] = ('LEGO', 'WEDO', 'SCRATCH', 'PYTHON')
    ddb_ctype['state'] = "readonly"
    ddb_ctype.current(0)

    def func(self):
        lst_course = ['下拉选中课程']
        lst_student = ['下拉选中学生']
        # print(dicts_course[ddb_ctype.get()])
        if dicts_course[ddb_ctype.get()]:
            for item in dicts_course[ddb_ctype.get()]:
                lst_course.append(item)
        if dicts_student[ddb_ctype.get()]:
            for item in dicts_student[ddb_ctype.get()]:
                lst_student.append(item)
        ddb_cname['value'] = lst_course
        ddb_cstu['value'] = lst_student
        if lst_course:
            ddb_cname.current(0)
        if lst_student:
            ddb_cstu.current(0)

    ddb_ctype.bind("<<ComboboxSelected>>", func)
    date_entry = Entry(addCourseAssociationWindow)
    date_entry.insert(0, datetime.datetime.now().strftime('%Y-%m-%d'))
    # stuName_entry.grid(row=0, column=1, padx=10, pady=5, ipadx=8)
    ddb_cstu.grid(row=0, column=1, padx=10, pady=5, ipadx=8)
    # courseName_entry.grid(row=1, column=1, padx=10, pady=5, ipadx=8)
    ddb_cname.grid(row=1, column=1, padx=10, pady=5, ipadx=8)
    ddb_ctype.grid(row=2, column=1, padx=10, pady=5)
    date_entry.grid(row=3, column=1, padx=10, pady=5, ipadx=8)

    add_btn = Button(addCourseAssociationWindow, text='添加',
                     command=lambda: add_course_association_to(ddb_cstu.get(), ddb_cname.get(),
                                                               ddb_ctype.get(),
                                                               date_entry.get()))
    add_btn.grid(row=4, column=5, padx=5, pady=5)
    addCourseAssociationWindow.mainloop()


# 接收add_course_association方法传递的数据交给数据库执行
def add_course_association_to(stuName, courseName, courseType, courseDate):
    """

    @param stuName: 学生姓名
    @param courseName: 课程名字
    @param courseType: 课程类型
    @param courseDate: 上课日期
    @return: 无
    """
    conn = get_connector()
    cur = get_cur(conn)
    # 添加学生课时
    sql1 = f'insert into t_course_association values(default,(select stu_id from t_student where stu_name = "{stuName}"),(select t_cid from t_course where t_cname = "{courseName}" and t_ctype = "{courseType.upper()}"),"{courseDate}")'
    # 更新学生课时数
    sql2 = f'update t_student_details set residue_sessions = residue_sessions-1,{courseType.lower()}_counts = {courseType.lower()}_counts+1 where t_stu_id = (select stu_id from t_student where stu_name = "{stuName}");'
    try:
        if stuName == '下拉选中学生' or courseName == '下拉选中课程':
            messagebox.showinfo(title='添加失败', message='内容输入有误！')
            return
        cur.execute(sql1)  # 执行插入的sql语句
        cur.execute(sql2)  # 执行插入的sql语句
        conn.commit()  # 提交到数据库执行
        messagebox.showinfo(title='添加成功', message='添加成功！')
    except BaseException:
        conn.rollback()  # 如果发生错误则回滚
        messagebox.showinfo(title='添加失败', message='内容输入有误！')
    conn_close(conn)
    cur_close(cur)


def add_course():
    addCourseWindow = Tk()
    addCourseWindow.title('添加课程')
    # addWindow.geometry('400x300')
    name_label = Label(addCourseWindow, text='课程名称：')
    type_label = Label(addCourseWindow, text='课程类别：')
    # sticky='w'，实现两个标签文本左对齐
    name_label.grid(row=0, column=0, padx=10, pady=5, sticky='w')
    type_label.grid(row=3, column=0, padx=10, pady=5, sticky='w')

    name_entry = Entry(addCourseWindow)
    # 课程类型下拉框
    ddb_ctype = ttk.Combobox(addCourseWindow)
    ddb_ctype['value'] = ('LEGO', 'WEDO', 'SCRATCH', 'PYTHON')
    ddb_ctype.current(1)
    ddb_ctype['state'] = "readonly"
    # type_entry = Entry(addCourseWindow)
    name_entry.grid(row=0, column=1, padx=10, pady=5, ipadx=8)
    # type_entry.grid(row=3, column=1, padx=10, pady=5)
    ddb_ctype.grid(row=3, column=1, padx=10, pady=5)

    add_btn = Button(addCourseWindow, text='添加',
                     command=lambda: add_course_to(name_entry.get(),
                                                   ddb_ctype.get()))
    add_btn.grid(row=4, column=5, padx=5, pady=5)
    addCourseWindow.mainloop()


def add_course_to(courseName, courseType):
    """

    @param courseName: 课程名字
    @param courseType: 课程类型
    @return:
    """
    conn = get_connector()
    cur = get_cur(conn)
    sql1 = f'insert into t_course values(default,"{courseName}","{courseType.upper()}")'
    # print("sql1:", sql1)
    try:
        cur.execute(sql1)  # 执行插入的sql语句
        conn.commit()  # 提交到数据库执行
        messagebox.showinfo(title='添加成功', message='添加成功！')
    except BaseException:
        conn.rollback()  # 如果发生错误则回滚
        messagebox.showinfo(title='添加失败', message='内容输入有误！')
    conn_close(conn)
    cur_close(cur)


def add_student():
    addWindow = Tk()
    addWindow.title('添加学生')
    # addWindow.geometry('400x300')
    name_label = Label(addWindow, text='姓名：')
    sex_label = Label(addWindow, text='性别：')
    age_label = Label(addWindow, text='年龄：')
    type_label = Label(addWindow, text='课程：')
    # sticky='w'，实现两个标签文本左对齐
    name_label.grid(row=0, column=0, padx=10, pady=5, sticky='w')
    sex_label.grid(row=1, column=0, padx=10, pady=5, sticky='w')
    age_label.grid(row=2, column=0, padx=10, pady=5, sticky='w')
    type_label.grid(row=3, column=0, padx=10, pady=5, sticky='w')

    name_entry = Entry(addWindow)
    # sex_entry = Entry(addWindow)
    # age_entry = Entry(addWindow)
    # 学生性别下拉框
    ddb_stu_sex = ttk.Combobox(addWindow)
    ddb_stu_sex['value'] = ('男', '女')
    ddb_stu_sex['state'] = "readonly"
    ddb_stu_sex.current(0)
    # 学生年龄下拉框
    ddb_stu_age = ttk.Combobox(addWindow)
    ddb_stu_age['value'] = ('3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16')
    ddb_stu_age['state'] = "readonly"
    ddb_stu_age.current(0)
    # 学生类型下拉框
    ddb_stu_type = ttk.Combobox(addWindow)
    ddb_stu_type['value'] = ('LEGO', 'WEDO', 'SCRATCH', 'PYTHON')
    ddb_stu_type.current(1)
    ddb_stu_type['state'] = "readonly"
    # type_entry = Entry(addWindow)
    name_entry.grid(row=0, column=1, padx=10, pady=5, ipadx=8)
    # sex_entry.grid(row=1, column=1, padx=10, pady=5)
    ddb_stu_sex.grid(row=1, column=1, padx=10, pady=5)
    # age_entry.grid(row=2, column=1, padx=10, pady=5)
    ddb_stu_age.grid(row=2, column=1, padx=10, pady=5)
    # type_entry.grid(row=3, column=1, padx=10, pady=5)
    ddb_stu_type.grid(row=3, column=1, padx=10, pady=5)

    add_btn = Button(addWindow, text='添加',
                     command=lambda: add_student_to(name_entry.get(), ddb_stu_sex.get(), ddb_stu_age.get(),
                                                    ddb_stu_type.get()))
    add_btn.grid(row=4, column=5, padx=5, pady=5)
    addWindow.mainloop()


def add_student_to(name, sex, age, typeCourse):
    """

    @param name: 学生姓名
    @param sex: 学生性别
    @param age: 学生年龄
    @param typeCourse: 学习的课程类型
    @return:
    """
    course_state = None
    if typeCourse.upper() == 'LEGO':
        course_state = 0
    elif typeCourse.upper() == 'WEDO':
        course_state = 1
    elif typeCourse.upper() == 'SCRATCH':
        course_state = 2
    elif typeCourse.upper() == 'PYTHON':
        course_state = 3
    if not course_state:
        messagebox.showinfo(title='添加失败', message='课程输入有误！')
        return
    conn = get_connector()
    cur = get_cur(conn)
    sql1 = f'insert into t_student values(default,"{name}","{sex}",{age},"{course_state}")'
    # print("sql1:", sql1)
    try:
        cur.execute(sql1)  # 执行插入的sql语句
        conn.commit()  # 提交到数据库执行
        messagebox.showinfo(title='添加成功', message='添加成功！')
    except BaseException:
        conn.rollback()  # 如果发生错误则回滚
        messagebox.showinfo(title='添加失败', message='内容输入有误！')
    conn_close(conn)
    cur_close(cur)


def add_student_details(stu_de_demo, stu_obj):
    """

    @param stu_de_demo: 预更新学生详细信息
    @param stu_obj: 学生准确基本信息
    @return:
    """
    # 默认学生详细信息模板
    stu_de = StudentDetails(None, '小神童', '18888888888', '中国', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '无', None)
    print(type(stu_de_demo.de_parents))
    print(type(stu_de_demo.de_total))
    if stu_de_demo.de_parents != '':
        stu_de.de_parents = stu_de_demo.de_parents
    if stu_de_demo.de_tel != '':
        stu_de.de_tel = stu_de_demo.de_tel
    if stu_de_demo.de_addr != '':
        stu_de.de_addr = stu_de_demo.de_addr
    if stu_de_demo.de_total != '':
        stu_de.de_total = stu_de_demo.de_total
    if stu_de_demo.de_res != '':
        stu_de.de_res = stu_de_demo.de_res
    if stu_de_demo.de_lc != '':
        stu_de.de_lc = stu_de_demo.de_lc
    if stu_de_demo.de_wc != '':
        stu_de.de_wc = stu_de_demo.de_wc
    if stu_de_demo.de_sc != '':
        stu_de.de_sc = stu_de_demo.de_sc
    if stu_de_demo.de_pc != '':
        stu_de.de_pc = stu_de_demo.de_pc
    if stu_de_demo.de_desc != '':
        stu_de.de_desc = stu_de_demo.de_desc
    if stu_de_demo.de_stu_image != '':
        stu_de.de_stu_image = stu_de_demo.de_stu_image
    if stu_de:
        print('stu true')
    else:
        print('stu false')
    if stu_obj:
        print('details true')
    else:
        print('details false')
    # print(stu_de.de_parents)
    # print(stu_obj.stu_id,stu_obj.stu_name,stu_obj.stu_sex,stu_obj.stu_age,stu_obj.stu_type)
    lego_state = 2
    if stu_de_demo.de_ls == '已完成':
        lego_state = 0
    elif stu_de_demo.de_ls == '进行中':
        lego_state = 1
    elif stu_de_demo.de_ls == '未开始':
        lego_state = 2

    wedo_state = 2
    if stu_de_demo.de_ws == '已完成':
        wedo_state = 0
    elif stu_de_demo.de_ws == '进行中':
        wedo_state = 1
    elif stu_de_demo.de_ws == '未开始':
        wedo_state = 2

    scratch_state = 2
    if stu_de_demo.de_ss == '已完成':
        scratch_state = 0
    elif stu_de_demo.de_ss == '进行中':
        scratch_state = 1
    elif stu_de_demo.de_ss == '未开始':
        scratch_state = 2

    python_state = 2
    if stu_de_demo.de_ps == '已完成':
        python_state = 0
    elif stu_de_demo.de_ps == '进行中':
        python_state = 1
    elif stu_de_demo.de_ps == '未开始':
        python_state = 2

    course_state = 0
    if stu_obj.stu_type.lower() == 'lego':
        course_state = 0
    elif stu_obj.stu_type.lower() == 'wedo':
        course_state = 1
    elif stu_obj.stu_type.lower() == 'scratch':
        course_state = 2
    elif stu_obj.stu_type.lower() == 'python':
        course_state = 3

    conn = get_connector()
    cur = get_cur(conn)
    sql1 = f'replace into t_student_details values(default,"{stu_de.de_parents}","{stu_de.de_tel}","{stu_de.de_addr}",{stu_de.de_total},{stu_de.de_res},{lego_state},{stu_de.de_lc},{wedo_state},{stu_de.de_wc},{scratch_state},{stu_de.de_sc},{python_state},{stu_de.de_pc},"{stu_de.de_desc}",{stu_obj.stu_id},"{stu_de.de_stu_image}");'
    sql2 = f'update t_student set stu_name = "{stu_obj.stu_name}",stu_sex = "{stu_obj.stu_sex}",stu_age = {stu_obj.stu_age},session_type = {course_state} where stu_id = {stu_obj.stu_id}'
    try:
        cur.execute(sql1)  # 执行插入的sql语句
        cur.execute(sql2)  # 执行插入的sql语句
        conn.commit()  # 提交到数据库执行
        messagebox.showinfo(title='更新成功', message='更新成功！')
    except BaseException:
        conn.rollback()  # 如果发生错误则回滚
        messagebox.showinfo(title='更新失败', message='内容输入有误！')
    conn_close(conn)
    cur_close(cur)


def search_teachers():
    pass


def exit_login(root):
    pass


def search_students(session_type):
    """

    @param session_type: 课程类型
    @return:
    """
    session_type_to = ''
    if session_type == 0:
        session_type_to = 'LEGO'
    elif session_type == 1:
        session_type_to = 'WEDO'
    elif session_type == 2:
        session_type_to = 'SCRATCH'
    elif session_type == 3:
        session_type_to = 'PYTHON'
    conn = get_connector()
    cur = get_cur(conn)
    data = get_data(cur, sqls=f'select * from t_student where session_type = {session_type}')
    # for i in data:
    #     print(i[0])
    conn_close(conn)
    cur_close(cur)

    def edit():
        x = tree.get_children()
        for item in x:  # Changing all children from root item
            tree.item(item, text="blub", values=("foo", "bar"))

    def delete(num):
        selected_item = tree.get_children()[num]
        tree.delete(selected_item)

    def treeviewSinglesClick(event):
        for child in treeCourse.get_children():
            treeCourse.delete(child)
        conn1 = get_connector()
        cur1 = get_cur(conn1)

        # print('双击')
        item_text = tree.item(tree.selection().__getitem__(0), "values")  # 当前选中的行数据
        data2 = get_data(cur1,
                         sqls=f'select t3.stu_name,t2.t_cname,t1.t_date from t_course_association t1 join t_student t3 on t3.stu_id = t1.t_stuid join t_course t2 on t1.t_courseid = t2.t_cid where t1.t_stuid = {item_text[0]} and t2.t_ctype = "{item_text[4]}" order by t1.t_date desc')  # 数据库中的数据
        # print(item_text)  # 输出所选行的第一列的值
        # print(data1)
        for j in data2[::-1]:
            treeCourse.insert('', 0, values=(j[1], j[2]))  # 给第0行添加数据，索引值可重复
        conn_close(conn1)
        cur_close(cur1)
        if event == 1:
            return data2

    def treeviewDoubleClick(event):  # 双击
        conn1 = get_connector()
        cur1 = get_cur(conn1)

        # print('双击')
        item_text = tree.item(tree.selection().__getitem__(0), "values")  # 当前选中的行数据
        data1 = get_data(cur1, sqls=f'select * from t_student_details where t_stu_id = {item_text[0]}')  # 数据库中的数据
        data2 = get_data(cur1,
                         sqls=f'select t3.stu_name,t2.t_cname,t1.t_date from t_course_association t1 join t_student t3 on t3.stu_id = t1.t_stuid join t_course t2 on t1.t_courseid = t2.t_cid where t1.t_stuid = {item_text[0]} and t2.t_ctype = "{item_text[4]}"')  # 数据库中的数据
        # print(item_text)  # 输出所选行的第一列的值
        # print(data1)
        conn_close(conn1)
        cur_close(cur1)
        # 打开学生详情窗口 包含报名信息、上课信息、家庭信息
        # detailsTk = Tk()
        detailsTk = Toplevel()
        # detailsTree = Treeview(tree_tk, show='headings')
        detailsTk.title('学生详情')
        detailsTk.geometry('800x600')
        la_stu_name = Label(detailsTk, text='姓名：')
        la_stu_sex = Label(detailsTk, text='性别：')
        la_stu_age = Label(detailsTk, text='年龄：')
        la_stu_course = Label(detailsTk, text='课程：')
        la_stu_parents = Label(detailsTk, text='家长：')
        la_stu_tel = Label(detailsTk, text='联系方式：')
        la_stu_addr = Label(detailsTk, text='家庭住址：')
        la_stu_total = Label(detailsTk, text='总课时：')
        la_stu_residue = Label(detailsTk, text='剩余课时：')
        la_stu_lego = Label(detailsTk, text='LEGO：')
        la_stu_lh = Label(detailsTk, text='累计课时：')
        la_stu_wedo = Label(detailsTk, text='WEDO：')
        la_stu_wh = Label(detailsTk, text='累计课时：')
        la_stu_scratch = Label(detailsTk, text='SCRATCH：')
        la_stu_sh = Label(detailsTk, text='累计课时：')
        la_stu_python = Label(detailsTk, text='PYTHON：')
        la_stu_ph = Label(detailsTk, text='累计课时：')
        la_stu_desc = Label(detailsTk, text='备注：')

        def chose_file(self, event=None):
            global img_ori
            ims_path = get_project_path()
            # 使用全局变量用来显示图片 img_ori
            if not os.path.exists(f'{ims_path}image_stu\\'):
                os.makedirs(f'{ims_path}image_stu\\')
            if self == 1:
                # 选择单个图片
                filename = askopenfilename(title='选择图片', filetypes=[(('JPG', '*.jpg')), ('All Files', '*')])
                ims = Image.open(filename)
                ims.save(f'{ims_path}image_stu\\{filename.split("/")[-1]}')
                conn_save_image = get_connector()
                cur_save_image = get_cur(conn_save_image)
                sql = f'update t_student_details set stu_image = "{filename.split("/")[-1]}" where t_stu_id = {data1[0][15]}'
                try:
                    cur_save_image.execute(sql)
                    conn_save_image.commit()
                except:
                    conn_save_image.rollback()
                    messagebox.showinfo(title='更新失败', message='图片路径有误！')
                    return
                finally:
                    cur_close(cur_save_image)
                    conn_close(conn_save_image)
                # file = ims.copy()  # 记录本次上传原始图片
            # print('图片名字：', filename.split('/')[-1])  # 截取最后一段/后的字符
            else:
                ims = Image.open(f'{ims_path}image_stu\\{self}')
            # print(f'{ims_path}image_stu\\{filename.split("/")[-1]}')  # 保存图片到指定目录

            # 图片尺寸规格化
            w, h = ims.size
            if w > h:
                # ime = ims.resize((125, int((125 * h / w))))
                ime = ims.resize((125, 175))
            else:
                # ime = ims.resize((int(175 * w / h), 175))
                ime = ims.resize((125, 175))

            img_ori = ImageTk.PhotoImage(ime)
            lb1 = Label(frm0, image=img_ori, bg="white")  # 用来显示图片
            lb1.grid(row=0, column=0)  # 设置图片的放置位置

        button_chose1 = Button(detailsTk, text='选择图片', font=('楷体', 14), bg='White', activebackground='White',
                               command=lambda: chose_file(1))
        button_chose1.grid(row=0, column=4)

        frm0 = Frame(detailsTk, width=125, height=175, bg="White")
        frm0.grid(row=1, column=4, rowspan=3)
        # 学生姓名
        la_stu_name.grid(row=0, column=0)
        # 学生性别
        la_stu_sex.grid(row=1, column=0)
        # 学生年龄
        la_stu_age.grid(row=2, column=0)
        # 当前课程类型
        la_stu_course.grid(row=3, column=0)
        # 学生家长
        la_stu_parents.grid(row=0, column=2)
        # 学生联系方式
        la_stu_tel.grid(row=1, column=2)
        # 学生家庭地址
        la_stu_addr.grid(row=2, column=2)
        # 学生总课时
        la_stu_total.grid(row=4, column=0)
        # 学生剩余课时
        la_stu_residue.grid(row=4, column=2)
        # LEGO状态
        la_stu_lego.grid(row=5, column=0)
        # 累计课时
        la_stu_lh.grid(row=5, column=2)
        # WEDO状态
        la_stu_wedo.grid(row=6, column=0)
        # 累计课时
        la_stu_wh.grid(row=6, column=2)
        # SCRATCH状态
        la_stu_scratch.grid(row=7, column=0)
        # 累计课时
        la_stu_sh.grid(row=7, column=2)
        # PYTHON状态
        la_stu_python.grid(row=8, column=0)
        # 累计课时
        la_stu_ph.grid(row=8, column=2)
        # 学生备注
        la_stu_desc.grid(row=4, column=4)

        en_stu_name = Entry(detailsTk)
        en_stu_age = Entry(detailsTk)
        en_stu_sex = Entry(detailsTk)
        en_stu_course = Entry(detailsTk)
        en_stu_parents = Entry(detailsTk)
        en_stu_tel = Entry(detailsTk)
        en_stu_addr = Entry(detailsTk)
        en_stu_total = Entry(detailsTk)
        en_stu_residue = Entry(detailsTk)
        # 课程状态下拉框
        en_stu_lego_ddb = ttk.Combobox(detailsTk, width=5, height=5)
        en_stu_lego_ddb['value'] = ('已完成', '进行中', '未开始')
        en_stu_lego_ddb['state'] = "readonly"
        en_stu_lh = Entry(detailsTk, width=5)

        # 课程状态下拉框
        en_stu_wedo_ddb = ttk.Combobox(detailsTk, width=5, height=5)
        en_stu_wedo_ddb['value'] = ('已完成', '进行中', '未开始')
        en_stu_wedo_ddb['state'] = "readonly"
        en_stu_wedo_ddb.current(2)

        en_stu_wh = Entry(detailsTk, width=5)
        # 课程状态下拉框
        en_stu_scratch_ddb = ttk.Combobox(detailsTk, width=5, height=5)
        en_stu_scratch_ddb['value'] = ('已完成', '进行中', '未开始')
        en_stu_scratch_ddb['state'] = "readonly"
        en_stu_scratch_ddb.current(2)

        en_stu_sh = Entry(detailsTk, width=5)
        # 课程状态下拉框
        en_stu_python_ddb = ttk.Combobox(detailsTk, width=5, height=5)
        en_stu_python_ddb['value'] = ('已完成', '进行中', '未开始')
        en_stu_python_ddb['state'] = "readonly"
        en_stu_python_ddb.current(2)

        en_stu_ph = Entry(detailsTk, width=5)
        en_stu_desc = Text(detailsTk, width=30, height=10)
        if item_text:
            en_stu_name.insert(0, item_text[1])
            en_stu_sex.insert(0, item_text[2])
            en_stu_age.insert(0, item_text[3])
            en_stu_course.insert(0, item_text[4])
            en_stu_parents.insert(0, data1[0][1])
            en_stu_tel.insert(0, data1[0][2])
            en_stu_addr.insert(0, data1[0][3])
            en_stu_total.insert(0, data1[0][4])
            en_stu_residue.insert(0, data1[0][5])
            en_stu_lego_ddb.current(data1[0][6])
            en_stu_lh.insert(0, data1[0][7])
            en_stu_wedo_ddb.current(data1[0][8])
            en_stu_wh.insert(0, data1[0][9])
            en_stu_scratch_ddb.current(data1[0][10])
            en_stu_sh.insert(0, data1[0][11])
            en_stu_python_ddb.current(data1[0][12])
            en_stu_ph.insert(0, data1[0][13])
            en_stu_desc.insert('0.0', data1[0][14])
            if data1[0][16]:
                chose_file(data1[0][16])
        # 学生姓名
        en_stu_name.grid(row=0, column=1, padx=15, pady=15, ipadx=2, ipady=2)
        # 学生性别
        en_stu_sex.grid(row=1, column=1, padx=15, pady=15, ipadx=2, ipady=2)
        # 学生年龄
        en_stu_age.grid(row=2, column=1, padx=15, pady=15, ipadx=2, ipady=2)
        # 当前课程类型
        en_stu_course.grid(row=3, column=1, padx=15, pady=15, ipadx=2, ipady=2)
        # 学生家长
        en_stu_parents.grid(row=0, column=3, padx=15, pady=15, ipadx=2, ipady=2)
        # 学生联系方式
        en_stu_tel.grid(row=1, column=3, padx=15, pady=15, ipadx=2, ipady=2)
        # 学生家庭地址
        en_stu_addr.grid(row=2, column=3, padx=15, pady=15, ipadx=2, ipady=2)
        # 学生总课时
        en_stu_total.grid(row=4, column=1, padx=15, pady=15, ipadx=2, ipady=2)
        # 学生剩余课时
        en_stu_residue.grid(row=4, column=3, padx=15, pady=15, ipadx=2, ipady=2)
        # LEGO状态
        en_stu_lego_ddb.grid(row=5, column=1, padx=15, pady=15, ipadx=1, ipady=1)
        # 累计课时
        en_stu_lh.grid(row=5, column=3, padx=15, pady=15, ipadx=2, ipady=2)
        # WEDO状态
        en_stu_wedo_ddb.grid(row=6, column=1, padx=15, pady=15, ipadx=2, ipady=2)
        # 累计课时
        en_stu_wh.grid(row=6, column=3, padx=15, pady=15, ipadx=2, ipady=2)
        # SCRATCH状态
        en_stu_scratch_ddb.grid(row=7, column=1, padx=15, pady=15, ipadx=2, ipady=2)
        # 累计课时
        en_stu_sh.grid(row=7, column=3, padx=15, pady=15, ipadx=2, ipady=2)
        # PYTHON状态
        en_stu_python_ddb.grid(row=8, column=1, padx=15, pady=15, ipadx=2, ipady=2)
        # 累计课时
        en_stu_ph.grid(row=8, column=3, padx=15, pady=15, ipadx=2, ipady=2)
        # 学生备注
        en_stu_desc.grid(row=5, column=4, padx=15, pady=15, ipadx=30, ipady=35, rowspan=4)

        update_btn = Button(detailsTk, text='提交更改', command=lambda: add_student_details(
            StudentDetails(None, en_stu_parents.get(), en_stu_tel.get(), en_stu_addr.get(), en_stu_total.get(),
                           en_stu_residue.get(), en_stu_lego_ddb.get(), en_stu_lh.get(), en_stu_wedo_ddb.get(),
                           en_stu_wh.get(),
                           en_stu_scratch_ddb.get(), en_stu_sh.get(), en_stu_python_ddb.get(), en_stu_ph.get(),
                           en_stu_desc.get('0.0', 'end'), data1[0][16])
            , Student(item_text[0], en_stu_name.get(), en_stu_sex.get(), en_stu_age.get(), en_stu_course.get())))
        update_btn.grid(row=9, column=2, columnspan=2, rowspan=2)

        detailsTk.mainloop()

    '''
    表格
    '''
    tree_tk = Tk()
    tree_tk.title('学生简介')
    tree = Treeview(tree_tk, show='headings')  # #创建表格对象
    tree["columns"] = ("序号", "姓名", "性别", "年龄", "类别")  # #定义列
    tree.column("序号", width=100)  # #设置列
    tree.column("姓名", width=100)
    tree.column("性别", width=100)
    tree.column("年龄", width=100)
    tree.column("类别", width=100)
    tree.heading("序号", text="序号")  # #设置显示的表头名
    tree.heading("姓名", text="姓名")
    tree.heading("性别", text="性别")
    tree.heading("年龄", text="年龄")
    tree.heading("类别", text="类别")
    start_label = Label(tree_tk, text='起始时间：')
    end_label = Label(tree_tk, text='结束时间：')
    start_label.grid(row=0, column=0)
    end_label.grid(row=1, column=0)
    starttime_entry = Entry(tree_tk)
    starttime_entry.insert(0, datetime.datetime.now().strftime('%Y-%m-%d'))
    endtime_entry = Entry(tree_tk)
    endtime_entry.insert(0, datetime.datetime.now().strftime('%Y-%m-%d'))

    def search_start_end(start, end):
        if treeCourse.get_children():
            data_course = treeviewSinglesClick(1)
            for child in treeCourse.get_children():
                treeCourse.delete(child)
            for j in data_course[::-1]:
                if start <= j[2] <= end:
                    treeCourse.insert('', 0, values=(j[1], j[2]))  # 给第0行添加数据，索引值可重复

    search_btn = Button(tree_tk, text='搜索',
                        command=lambda: search_start_end(starttime_entry.get(), endtime_entry.get()))
    starttime_entry.grid(row=0, column=1)
    endtime_entry.grid(row=1, column=1)
    search_btn.grid(row=2, column=0, columnspan=2)
    for i in data[::-1]:
        tree.insert('', 0, values=(i[0], i[1], i[2], i[3], session_type_to))  # 给第0行添加数据，索引值可重复
    treeCourse = Treeview(tree_tk, show='headings')  # #创建表格对象
    treeCourse["columns"] = ("课程名称", "上课时间")  # #定义列
    treeCourse.column("课程名称", width=100)  # #设置列
    treeCourse.column("上课时间", width=100)
    treeCourse.heading("课程名称", text="课程名称")  # #设置显示的表头名
    treeCourse.heading("上课时间", text="上课时间")
    """for j in data2[::-1]:
        treeCourse.insert('', 0, values=(j[1], j[2]))  # 给第0行添加数据，索引值可重复"""
    # treeCourse.pack()
    treeCourse.grid(row=0, column=2, rowspan=3, padx=0)
    tree.bind('<Double-1>', treeviewDoubleClick)
    tree.bind('<ButtonRelease-1>', treeviewSinglesClick)
    # tree.pack()
    tree.grid(row=3, column=0, columnspan=3)
